/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.synjones.pay.bank.wisedu.service;

import com.alibaba.fastjson.JSON;
import com.synjones.core.util.AmtHelper;
import com.synjones.core.util.MapUtil;
import com.synjones.pay.bank.api.AbstractBankJumpImpl;
import com.synjones.pay.bank.wisedu.bean.WiseduPayConst;
import com.synjones.pay.bank.wisedu.bean.WiseduPayReqBean;
import com.synjones.pay.bank.wisedu.bean.WiseduPayRespBean;
import com.synjones.pay.bank.wisedu.bean.WiseduPayReturnReqBean;
import com.synjones.pay.bank.wx.bean.wisrecharge.YktRechargeWisReqBean;
import com.synjones.pay.bank.wx.bean.common.ExtendedServApiUrl;
import com.synjones.pay.bank.wx.bean.common.WxResponseBean;
import com.synjones.pay.bank.wx.helper.ExtendedServHelper;

import com.synjones.pay.model.common.CommonConstant;
import com.synjones.pay.model.common.ResponseBean;
import com.synjones.pay.model.context.IPayContext;
import com.synjones.pay.model.context.StatusInfo;
import com.synjones.pay.model.recharge.RechargeTradeBean;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liubinqiang
 * @date 2017-5-20 13:29:49
 * @version V1.0
 * @desc 金智支付
 */
public class WisBankJumpImpl extends AbstractBankJumpImpl {

    private final static Logger logger = LoggerFactory.getLogger(WisBankJumpImpl.class);

    private static final String SYS_CERT = "tvBAAvQhyAIIBVt6w8m9ieCSgLP4wEyGUzcSveAHZl0eM76mPoZm79VSVNsfxFt7jIFKbWYlnqyiSUtwwWyxD46mXAQKa1mMhjW3FpFYLCKtMSjRn5GNp3dTyKQL48kt";
    private static final String URL = "http://pay.dlmu.edu.cn/pay/itemDeal3.html";
    private static final String JUMP_URL = "http://pay.dlmu.edu.cn/pay/dealPay.html?pwd=";
    private static final String PAY_SYS_ID = "0005";
    private static final String PAY_ITEM_ID = "0005-01";

    //金智回调通知地址
    private static final String RETURN_URL = "http://epay.dlmu.edu.cn/m/recWisPage";

    private String payPwd = "";

    @Override
    public Map<String, String> doPay(IPayContext ctx) {
        Map<String, String> reqMap = MapUtil.newInstance();
        String zfm = new StringBuilder(JUMP_URL).append(processPay(ctx)).toString();
        reqMap.put(CommonConstant.JUMPL_URL, zfm);
        return reqMap;
    }

    private String processPay(IPayContext ctx) {
        //生成请求数据
        Map<String, String> respMap = buildSendData(ctx);
        //请求金智，生成支付码
        String respStr = sendData(respMap.get(CommonConstant.TRADE_OBJ));
        //取到支付码
        return getPayPassword(respStr);
    }

    @Override
    public String getJumpUrl() {
        return null;
    }

    @Override
    public Map<String, String> buildSendData(IPayContext ctx) {

        //从支付系统取参数
        RechargeTradeBean rechargeBean = ctx.getRequest().get(CommonConstant.TRADE_OBJ);
        WiseduPayReqBean reqBean = new WiseduPayReqBean();
        reqBean.setSysId(PAY_SYS_ID);
        reqBean.setItemId(PAY_ITEM_ID);
        reqBean.setOtherId("");

//        reqBean.setObjId("sn20170531-0232");
//        reqBean.setObjName("测试缴费0531411");
//        String amt = String.valueOf(AmtHelper.poingToYuan("13"));
        String sno = rechargeBean.getAccName();
        String cardno = rechargeBean.getAccName();
        //学工号
        reqBean.setObjId(sno);
        //姓名
        reqBean.setObjName(rechargeBean.getAccName());
        StringBuilder specialValue = new StringBuilder();
        specialValue.append(getDeptBySno(sno)).append("/").append(PAY_SYS_ID).append("/").append(cardno);
        reqBean.setSpecialValue(specialValue.toString());
        String amt = String.valueOf(AmtHelper.poingToYuan(rechargeBean.getAmount()));
        reqBean.setAmount(amt);
        reqBean.setReturnURL(RETURN_URL);
        String requestStr = reqBean.genPara(SYS_CERT);
        Map<String, String> respMap = new HashMap<>();
        respMap.put(CommonConstant.TRADE_OBJ, requestStr);
        return respMap;
    }

    private String getDeptBySno(String sno) {
        return ExtendedServHelper.getDeptBySno(sno);
    }

    /**
     * 金智入账
     *
     * @param reqBean
     * @return
     */
    public WxResponseBean wisRecharge(YktRechargeWisReqBean reqBean) {
        String responseStr = ExtendedServHelper.postToServer(ExtendedServApiUrl.WIS_RECHARGE, JSON.toJSONString(reqBean));
        WxResponseBean responseBean = JSON.parseObject(responseStr, WxResponseBean.class);
        return ExtendedServHelper.commonResponseBean(responseBean);
    }

    /*    
    {"returnCode":"00","payPassword":"B9B525A92299404E","projectId":751,"itemId":"0005-01","amount":"1.00",
    "payId":2046410,"sign":"73f5cd5d95c31f5603d85fc5315aef0b","objName":"dfs","sysId":"0005","specialValue":"","objId":"123","otherId":"","returnURL":""}
     */
    public String sendData(String requestStr) {
        logger.info("提交充值信息{}", requestStr);
        String responseStr = "";
        try {
            URL url = new URL(URL);
            URLConnection conn = url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream out = conn.getOutputStream();
            out.write(requestStr.getBytes(WiseduPayConst.ENCODE_TYPE));
            InputStream in = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(in, WiseduPayConst.ENCODE_TYPE);
            char[] buf = new char[1024];
            int count = isr.read(buf);
            responseStr = new String(buf, 0, count);
        } catch (Exception e) {
            logger.info("WiseduDirectorImpl.sendData:{}", e.getMessage());
        }
        logger.info("WiseduDirectorImpl.sendData.responseStr={}", responseStr);
        return responseStr;
    }

    private String getPayPassword(String resp) {
        if (resp != null && resp.contains("")) {
            WiseduPayRespBean respBean = JSON.parseObject(resp, WiseduPayRespBean.class);
            if (respBean != null) {
                return respBean.getPayPassword();
            }
        }
        return "";
    }

    @Override
    public ResponseBean resolveRespData(Map<String, String> resMap) {
        WiseduPayReturnReqBean bean = getReturnBean(resMap);
        ResponseBean.Builder builder = new ResponseBean.Builder();
        //支付状态1 已完成缴费2 结单如果是结单情况，金额会小于请求支付时的金额
        String wisStatus = bean.getStatus();
        logger.info("resolveRespData:wisStatus=" + wisStatus);
        if (wisStatus.equals("1") || wisStatus.equals("2")) {
            builder.statusCode(StatusInfo._0000.code());
        } else {
            builder.statusCode(StatusInfo._1003.code());
        }
        //订单号
        builder.orderNo(bean.getPayId());
        //流水号
        builder.serialNo(bean.getObjId());
        //已付金额
        String amt = String.valueOf(AmtHelper.yuanToPoint(bean.getPaid()));
        builder.amount(amt);
        ResponseBean responseBean = builder.builder();
        return responseBean;
    }

    /**
     * 从map得到WiseduPayReturnReqBean
     *
     * @param resMap
     * @return
     */
    private WiseduPayReturnReqBean getReturnBean(Map<String, String> resMap) {
        WiseduPayReturnReqBean bean = new WiseduPayReturnReqBean();
        bean.setSign(resMap.get("sign"));
        bean.setVersion(resMap.get("version"));
        bean.setSysId(resMap.get("sysId"));
        bean.setItemId(resMap.get("itemId"));
        bean.setObjId(resMap.get("objId"));
        bean.setOtherId(resMap.get("otherId"));
        bean.setObjName(resMap.get("objName"));
        bean.setAmount(resMap.get("amount"));
        bean.setPaid(resMap.get("paid"));
        bean.setRefund(resMap.get("refund"));
        bean.setOverTime(resMap.get("overTime"));
        bean.setStatus(resMap.get("status"));
        bean.setProjectId(resMap.get("projectId"));
        bean.setPayId(resMap.get("payId"));
        bean.setPayPassword(resMap.get("payPassword"));
        bean.setSpecialValue(resMap.get("specialValue"));
        bean.setPayType(resMap.get("payType"));
        return bean;
    }

    @Override
    public boolean verifyRespSign(Map<String, String> resMap) {
        WiseduPayReturnReqBean bean = getReturnBean(resMap);
        String genSign = bean.genSign(SYS_CERT);
        logger.info("verifyRespSign:genSign=" + genSign + ",sign=" + bean.getSign());
        return genSign.equals(bean.getSign());
    }

}
